package com.hygj.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.hygj.pojo.Role;
import com.hygj.pojo.User;
import com.hygj.service.RoleService;
import com.hygj.service.UserRoleService;
import com.hygj.service.UserService;
import com.hygj.util.MD5Utils;
import com.hygj.util.PageUtil;

/**
 * Shiro登录认证 原理： 1、用户提交 用户名和密码 2、 shiro 封装令牌 3、realm 通过用户名将密码查询返回 4、shiro
 * 自动去比较查询出密码和用户输入密码是否一致 5、进行登陆控制
 * 
 * @author hygl
 *
 */
@Controller
@RequestMapping
public class UserController {

	@Autowired
	private UserService userService;
    
	@Resource
	private UserRoleService userRoleService;
	
	@Resource
	private  RoleService roleService;
	
	/**
	 * 验证用户名和密码
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("checkLogin")
	public String doLogin(HttpServletRequest request, ModelMap modelMap, User user) {
		if ((user.getUsername() == null || user.getUsername().length() <= 0)
				&& (user.getPassword() == null || user.getPassword().length() <= 0)) {
			modelMap.put("no", "用户名或者密码不能为空！");
			return "login";
		} else {
			// 取得用户名
			String username = request.getParameter("username");
			// 取得 密码，并用MD5加密
			String password = MD5Utils.getMD5String(request.getParameter("password"));
			// 用户名/密码的认证机制,并创建令牌
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			// 通过SecurityUtils工具类，获取当前的用户，然后通过调用login方法提交认证
			Subject subject = SecurityUtils.getSubject();
			try {
				System.out.println("----------开始验证------------------");

				// 验证角色和权限,进入===【ShiroRealmShiro.java】===身份登录认证
				subject.login(token);
				// 获取session
				//Session session = subject.getSession();
				//System.out.println("======>ID:" + session.getId() + "=====>sessionHost" + session.getHost()
						//+ "=====>sessionTimeout" + session.getTimeout());
			} catch (Exception e) {
				System.out.println("-----------验证失败--------------");
				e.printStackTrace();
				modelMap.put("msg", "用户或密码错误！");
				return "login";
			}

			System.out.println("-----------验证成功--------------");
			modelMap.put("name", user.getUsername());
			return "redirect:/admin";
		}

	}

	/**
	 * 增加用户与角色的关系，并保存用户
	 * String roles  是从表单提交带来的参数
	 * @param login
	 * @return
	 */
	@RequestMapping("userInsert")
	public String userInsert(User user, @RequestParam(value= "userrole", defaultValue= "") String[] roles) {
		//StringUtils.join把数组中的元素连接成一个字符串返回。
		userService.saveUserwithRole(user, StringUtils.join(roles,","));
		return "redirect:getUserWithRoleAll";
	}
	
	/**
	 * 查询用户和角色(用于菜单【用户信息】列表显示)
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("getUserWithRoleAll")
	public String getUserRoleAll(Map<String, Object> map, HttpServletRequest request) {
		Map<String, Object> params = new HashMap<String, Object>();
		//第一：先分页查询
		PageUtil<User> page = userService.page(request, 10, params);
		//第二：把page里的数据拿出开放进【list】集合里
		List<User> users = page.getLists();
		for(User user: users){
			user.setRoles(userRoleService.listRoles(user.getId()));
		}
		
		map.put("page", page);
		return "logins/UserShow";
	}
	
	
	/**
	 * 查询  用户信息【用户名、密码、角色名称、备注】回显 ----修改用户信息用
	 *
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("getUserUpdate")
	public String getUserRoleAlls(@RequestParam("id") Integer id, Map<String, Object> map) {
	    //查询用户信息
		User user = userService.getById("getById", id);
		
	    //查询角色信息
		Map<String, Object> params = new HashMap<String, Object>();
		List<Role> page = roleService.listAll("listAll", params);
		// list转换成Map
		Map<String, String> _r = new HashMap<String, String>();
		for (Role role : page) {
			_r.put("" + role.getRid(), role.getRole_name());
		}
		//通过上面查询的user信息，获取 该用户的角色 --getListRoles（pojo一个用户可以有多个角色）
		List<Role> userRoles = user.getRoles();
		Map<String, String> userRoleCheck = new HashMap<String, String>();
		for(Role role: userRoles){
			userRoleCheck.put(role.getRid()  + "", role.getRole_name());
		}
		
		map.put("userRoleCheck", userRoleCheck);
		map.put("roles", _r);
	    map.put("users", user);
		return "logins/UserUpdate";
	}
	
	
	
	/**
	 * 用户信息--修改
	 * @param user
	 * @param roles
	 * @return
	 */
	@RequestMapping("updateUserRoleAlls")
	public String updateUserRoleAlls(User user, @RequestParam(value= "userrole", defaultValue= "") String[] roles){
		
		userService.saveUserwithRole(user, StringUtils.join(roles,","));
		return "redirect:getUserWithRoleAll";
	}
	
	
	

	/**
	 * 查询全部
	 * 
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("getLoginAll")
	public String getLoginAll(Map<String, Object> map, HttpServletRequest request) {
		Map<String, Object> params = new HashMap<String, Object>();
		PageUtil<User> page = userService.page(request, 10, params);
		map.put("page", page);
		return "logins/registerShow";
	}
    
	/**
	 * 删除
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("deleteLogin")
	public String deleteLogin(@RequestParam("id") Integer id) {
		userRoleService.delete("delete", id);
		userService.delete("delete", id);
		return "redirect:getUserWithRoleAll";
	}

	/**
	 * 给用户赋予角色
	 * 
	 * @return
	 */
	@RequestMapping("grantUserRole")
	public String grantUserRole() {

		return "";
	}

	/**
	 * 退出
	 * 
	 * @return
	 */
	@RequestMapping("logout")
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "login";
	}

}
